﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Inspection.Helper
{
    public static class ExtentionMethod
    {
        /// <summary>
        /// IP地址校验基于正则表达式
        /// </summary>
        /// <param name="ip">IP地址字符串</param>
        /// <returns>如果符合IP地址的校验规则则返回true,否则返回false</returns>
        public static bool IsIpAdress(this string ip)
        {
            if (string.IsNullOrEmpty(ip) || ip.Length < 7 || ip.Length > 15)
            {
                return false;
            }
            string regformat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(ip);
        }

        /// <summary>
        /// Delete files older than the specified time in the specified path
        /// </summary>
        /// <param name="fileDirectory">Folder where the path is stored =>存放路径的文件夹</param>
        /// <param name="overDueDays">Exceeded specified time=>超过的指定时间</param>
        public static void DeleteFile(string fileDirectory, int overDueDays)
        {
            DateTime NowTime = DateTime.Now;
            if (!Directory.Exists(fileDirectory)) return;
            string[] folderInfo = Directory.GetDirectories(fileDirectory);
            string[] files = Directory.GetFiles(fileDirectory, "*.*", System.IO.SearchOption.AllDirectories);
            foreach (var file in files)
            {
                FileInfo fileInfo = new FileInfo(file);
                TimeSpan t = NowTime - fileInfo.CreationTime;
                int day = t.Days;
                if (day > overDueDays)
                    File.Delete(file);
            }
        }
    }

}
